package com.iflytek.cosmo.ocr.common.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 *
 * Description:服务器地址工具类
 *
 */
public class InetAddressUtil {
    /**
     * 多网卡机器，获取所有多网卡地址
     *
     * @return
     * @author xqxia3
     * @date 2018年4月23日
     */
    public static Enumeration<InetAddress> getAddresses() {
        Enumeration<InetAddress> addresss = null;
        try {
            Enumeration<NetworkInterface> interfaces = null;
            interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();
                addresss = ni.getInetAddresses();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return addresss;
    }

    /**
     * 获取多网卡网络接口
     *
     * @return
     * @author xqxia3
     * @date 2018年4月23日
     */
    public static Enumeration<NetworkInterface> getMoreInterfaces() {
        Enumeration<NetworkInterface> interfaces = null;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return interfaces;
    }

    /**
     * 判断本地是否为多网卡服务器
     *
     * @return
     * @author xqxia3
     * @date 2018年4月23日
     */
    public static Boolean isMoreAddresses() {
        Boolean flag = false;
        Enumeration<NetworkInterface> interfaces = getMoreInterfaces();
        Enumeration<InetAddress> addresss = getAddresses();
        if (interfaces.hasMoreElements() || addresss.hasMoreElements()) {
            flag = true;
        }

        return flag;
    }

    /**
     * 从HttpServletRequest 获取ip地址
     *
     * @param request
     * @return 远端ip地址
     */
    public static String getRemoteIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
}
